package com.shujia.akka.clientAndServer

import akka.actor.{Actor, ActorRef, ActorSelection, ActorSystem, Props}
import com.typesafe.config.{Config, ConfigFactory}

import scala.io.StdIn

object Client extends App {

  //  val clientHost = "localhost"
  //  val clientPort = 9999

  val (clientHost, clientPort,serverHost, serverPort) = ("127.0.0.1", 9999,"127.0.0.1", 8888)


  private val config: Config = ConfigFactory.parseString(
    s"""
       |akka.actor.provider="akka.remote.RemoteActorRefProvider"
       |akka.remote.netty.tcp.hostname=$clientHost
       |akka.remote.netty.tcp.port=$clientPort
       |""".stripMargin
  )

  private val tongTongSystem: ActorSystem = ActorSystem("tongTong", config)

  private val clientRef: ActorRef = tongTongSystem.actorOf(Props(new Client(serverHost, serverPort)), "client")

//  while (true){
//    println("请输入您的消息：")
//    val message: String = StdIn.readLine()
//    clientRef ! message
//  }
  clientRef ! "start"

}

class Client(serverHost:String, serverPort:Int) extends Actor {

  // 上下文对象，从Actor中获取的
  private val selection: ActorSelection = context.actorSelection(s"akka.tcp://tongTongServer@$serverHost:$serverPort/user/server")

  override def receive: Receive = {
    case "start" => {
      println("童童聊天室启动了..")
      println("请输入消息：")
      self ! StdIn.readLine()
    }
//    case message:String => {
//      // 将客户端读取的消息发送给服务端 => 给定服务端的IP和地址
//      println("client:"+message)
//      selection ! message
//    }

    case message:String => {
      println("Client:"+message)
      // 将数据发送给服务端
      selection ! ClientMessage(message)
    }
    case ServerMessage(message) => {
      println("Server:"+message)
      println("回复信息：")
      selection ! StdIn.readLine()
    }
  }
}